package com.workManager.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.workManager.exception.BusinessException;
import com.workManager.mapper.TbProjectMapper;
import com.workManager.mapper.TbProjectTotalCostMapper;
import com.workManager.pojo.TbProject;
import com.workManager.pojo.TbProjectTotalCost;
import com.workManager.util.ExcelReadUtil;
import com.workManager.vo.ProjectTotalCostVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by strangevy on 2017/6/26
 */
@Service
public class ProjectTotalCostServiceImpl implements ProjectTotalCostService {


    @Autowired
    private TbProjectTotalCostMapper tbProjectTotalCostMapper;

    @Autowired
    private TbProjectMapper tbProjectMapper;

    @Transactional
    public void uploadExcel(String name, MultipartFile file) throws Exception {

        List<String[]> fileData = ExcelReadUtil.excelToList(name,file.getInputStream());

        String[] tableHead = fileData.get(0);
        String[] headTitle = {"项目编号", "年月", "总成本"};
        for (int i = 0; i < headTitle.length; i++) {
            String headItem = tableHead[i];
            if (!headItem.equals(headTitle[i])) {
                throw new BusinessException("表格格式不正确！请检查表格格式重新上传。(行：1，列：" + (i + 1) + ")");
            }
        }

        //匹配金额
        String reg = "^-?[0-9]{1,8}(.[0-9]{1,2})?$";

        for (int i = 1; i < fileData.size(); i++) {
            String[] rowData = fileData.get(i);

            //检查是否空行
            if (ExcelReadUtil.isBlankRow(rowData)) {
                continue;
            }
            if (rowData[0] == null || "".equals(rowData[0])) {
                throw new BusinessException("项目编号不能为空！请检查数据重新上传。(行：" + (i+1) + "，列：1)");
            }
            if (rowData[1] == null || "".equals(rowData[1])) {
                throw new BusinessException("年月不能为空！请检查数据重新上传。(行：" + (i+1) + "，列：2)");
            }
            if (rowData[1].indexOf("-")!=4) {
                throw new BusinessException("年月格式不正确，应为YYYY-MM！请检查数据重新上传。(行：" + (i+1) + "，列：2)");
            }
            if (rowData[2] == null || "".equals(rowData[2])) {
                throw new BusinessException("总成本不能为空！请检查数据重新上传。(行：" + (i+1) + "，列：3)");
            }



            String projectCode = rowData[0].trim();
            String salMonth = rowData[1].trim();
            String[] arr = salMonth.split("-");
            salMonth = arr[0]+"-"+(arr[1].length()==2?arr[1]:"0"+arr[1]);
            String totalAmount = rowData[2].trim();

            if (!totalAmount.matches(reg)) {
                throw new BusinessException("金额请精确到小数点后2位，整数位不大于8位(行：" + (i+1) + "，列：5)");
            }


            TbProjectTotalCost projectTotalCost = new TbProjectTotalCost();
            TbProject tbProject = tbProjectMapper.selectByProjectCode(projectCode);

            if (tbProject == null) {
                throw new BusinessException("项目编号：" + projectCode + " 不存在！请检查数据重新上传。(行：" + (i+1) + "，列：4)");
            }

            projectTotalCost.setSalMonth(salMonth);
            projectTotalCost.setTotalAmount(new BigDecimal(totalAmount));
            projectTotalCost.setProjectId(tbProject.getProjectId());
            projectTotalCost.setCreateDate(new Date());

            Map<String, Object> param = new HashMap<String, Object>();
            param.put("projectCode",projectCode);
            param.put("projectName",tbProject.getProjectName());
            param.put("salMonth",salMonth);
            List<TbProjectTotalCost> cost = tbProjectTotalCostMapper.querySingle(param);
            if (cost==null||cost.size()==0) {
                tbProjectTotalCostMapper.insert(projectTotalCost);
            } else {
                projectTotalCost.setId(cost.get(0).getId());
                tbProjectTotalCostMapper.updateByPrimaryKey(projectTotalCost);
            }

        }
    }

    public PageInfo<ProjectTotalCostVo> countLaberCost(Map<String, Object> queryParam) {
        int pageno = !queryParam.containsKey("pagenum")||queryParam.get("pagenum")==null?1:Integer.parseInt(queryParam.get("pagenum").toString());
        int pagesize = !queryParam.containsKey("pagesize")||queryParam.get("pagesize")==null?10:Integer.parseInt(queryParam.get("pagesize").toString());
        PageHelper.startPage(pageno,pagesize);
        List<ProjectTotalCostVo> projectTotalCostList = tbProjectTotalCostMapper.query(queryParam);
        PageInfo<ProjectTotalCostVo> pageInfo = new PageInfo<ProjectTotalCostVo>(projectTotalCostList);
        return pageInfo;
    }

    public List<ProjectTotalCostVo> selectByProjectCode(String projectCode) {
        return tbProjectTotalCostMapper.selectByProjectCode(projectCode);
    }


}
